<template>
  <refresh-list
    ref="refreshList"
    :enable-pull-refresh="false"
    @pull-load="onListLoad"
  > 
  </refresh-list>
</template>

<script>
import RefreshList from '@/components/refresh-list/RefreshList'
import { apiGetSearchResult } from '@/api/search'
export default {
  name: 'SearchResultBase',
  inject: ['rootThemeColor'],
  components: {
    RefreshList
  },
  props: {
    keyword: {
      type: String
    },
    searchType: {
      type: String,
      default: 'media_bangumi'
    },
    order: {
      type: String,
      default: 'totalrank'
    }
  },
  data () {
    return {
      data: [],
      totalPage: 0,
      currentPage: 1,
      pageSize: 20
    }
  },
  created () {
    this.getData()
  },
  methods: {
    onListLoad () {
      clearTimeout(this.listTimeout)
      if (!this.$refs.refreshList.isFinished()) {
        this.currentPage++
        this.listTimeout = setTimeout(() => {
          this.getData()
        }, 1000)
      }
    },
    getData ({ url = '/search/byKeyword', data = {} } = {}) {
      const p = Object.assign({}, {
        keyword: this.keyword,
        page: this.currentPage,
        search_type: this.searchType,
        order: this.order,
        pagesize: this.pageSize
      }, data)
      apiGetSearchResult({ url, data: p }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          const { result, numPages, page } = data
          this.currentPage = page
          this.totalPage = numPages
          if (numPages > 0) {
            this.data.push(...result)
          } else {
            this.$refs.refreshList.completeLoad()
          }
          if (this.currentPage === this.totalPage) {
            this.$refs.refreshList.completeLoad()
          }
        } else {
          this.$refs.refreshList.completeLoad()
        }
      }).catch(err => {
        console.log(err)
        this.$refs.refreshList.showError()
      }).finally(() => {
        this.$refs.refreshList.stopLoad()
      })
    }
  }
}
</script>

<style>

</style>
